package com.hlhj.funlike_business.activity;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hlhj.funlike_business.R;
import com.hlhj.funlike_business.bean.BitmapEvent;
import com.hlhj.funlike_business.bean.MsgBean;
import com.hlhj.funlike_business.bean.ShopInfoBean;
import com.hlhj.funlike_business.bean.TakeTypeBean;
import com.hlhj.funlike_business.bean.UpImgBean;
import com.hlhj.funlike_business.data.SPUser;
import com.hlhj.funlike_business.presenter.SettingsPresenter;
import com.hlhj.funlike_business.utils.AbulmCameraDialog;
import com.hlhj.funlike_business.utils.Dialog;
import com.hlhj.funlike_business.utils.FileUtils;
import com.hlhj.funlike_business.utils.MyGlideEngin;
import com.hlhj.funlike_business.utils.TimeDialog;
import com.hlhj.funlike_business.utils.UpImgDialog;
import com.hlhj.funlike_business.views.SettingsView;
import com.huantansheng.easyphotos.EasyPhotos;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class SettingsAty extends BaseActivity<SettingsView, SettingsPresenter> implements SettingsView, AbulmCameraDialog.OnItemClickListener,TimeDialog.ResultCallBack {
    private ImageView img_back,img_cover;
    private TextView tv_title,tv_takeType,tv_shopname,tv_advert,tv_tel,tv_cricle,tv_endtime,tv_starttime,tv_address;
    private RelativeLayout rl_photo, rl_takeservice, rl_name, rl_advert, rl_cover, rl_address, rl_phone, rl_takecircle, rl_businesstime, rl_shopaptitude;
    private Dialog dialog;
    private final int TAKE_PHOTO = 2;

//    private static final int CROP_PHOTO = 2;
//    private static final int PICK_PIC = 3;
//    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE1 = 4;
//    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 5;
//    private File output;
//    private Uri imageUri;
    private UpImgDialog imgDialog;

    private AbulmCameraDialog abulmCameraDialog;
    private SPUser spUser;
    private String startime = "";
    private String endtime = "";
    private String advert,name,phoneNum;
    public static String freight;
    public static int freight_long;
    private int circle;
    public static List<TakeTypeBean.DataBean> dataBeanList = new ArrayList<>();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getContentId() {
        return R.layout.aty_settings;
    }

    @Override
    protected void initData() {
        tv_title.setText("店铺设置");
        imgDialog=new UpImgDialog(this);

        dialog = new Dialog();
        abulmCameraDialog = new AbulmCameraDialog(this);
        abulmCameraDialog.setOnItemClickListener(this);
        dialog.setCancelable(true);

        spUser = new SPUser(getApplication());
    }

    @NotNull
    @Override
    public SettingsView bindView() {
        return this;
    }

    @NotNull
    @Override
    public SettingsPresenter createPresenter() {
        return new SettingsPresenter();
    }

    @Override
    public void initView() {
        img_back = findViewById(R.id.img_back);
        tv_title = findViewById(R.id.tv_title);
        rl_photo = findViewById(R.id.rl_photo);
        rl_takeservice = findViewById(R.id.rl_takeservice);
        rl_name = findViewById(R.id.rl_name);
        rl_advert = findViewById(R.id.rl_advert);
        rl_cover = findViewById(R.id.rl_cover);
        rl_address = findViewById(R.id.rl_address);
        rl_phone = findViewById(R.id.rl_phone);
        rl_takecircle = findViewById(R.id.rl_takecircle);
        rl_businesstime = findViewById(R.id.rl_businesstime);
        rl_shopaptitude = findViewById(R.id.rl_shopaptitude);
        img_cover = findViewById(R.id.img_cover);
        tv_takeType = findViewById(R.id.tv_takeType);
        tv_shopname = findViewById(R.id.tv_shopname);
        tv_advert = findViewById(R.id.tv_advert);
        tv_tel = findViewById(R.id.tv_tel);
        tv_cricle = findViewById(R.id.tv_cricle);
        tv_endtime = findViewById(R.id.tv_endtime);
        tv_starttime = findViewById(R.id.tv_starttime);
        tv_address = findViewById(R.id.tv_address);
    }

    @Override
    public void logicStart() {
        getData();
        getPresenter().LoadShopInfo(this);
        getPresenter().LoadTakeType(this);
    }

    @Override
    public void setListener() {
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky("刷新我的界面");
                finish();
            }
        });
        rl_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingsAty.this, PhotoAty.class);
                intent.putExtra("title","相册");
                startActivity(intent);
            }
        });
        rl_takeservice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show(getFragmentManager(), "");
            }
        });
        rl_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingsAty.this, ShopNameAty.class);
                intent.putExtra("name",name);
                startActivity(intent);
            }
        });
        rl_advert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingsAty.this, AdvertAty.class);
                intent.putExtra("advert",advert);
                startActivity(intent);
            }
        });
        rl_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                abulmCameraDialog.showDialog();
            }
        });
        rl_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingsAty.this, PhoneNumberAty.class);
                intent.putExtra("phoneNum",phoneNum);
                startActivity(intent);
            }
        });
        rl_takecircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingsAty.this, TakeCircleAty.class);
                intent.putExtra("circle",circle);
                startActivity(intent);
            }
        });
        rl_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SettingsAty.this, MyMapAty.class);
                startActivityForResult(intent,1000);
            }
        });
        rl_businesstime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTime();
            }
        });
        rl_shopaptitude.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SettingsAty.this, PhotoAty.class);
                intent.putExtra("title","店铺资质");
                startActivity(intent);
            }
        });

        dialog.setLisenter(new Dialog.getTakeType() {
            @Override
            public void getType(String type, int id, String freight, int freight_long) {
                tv_takeType.setText(type);
                Log.e("zy",id + "-" + freight + "-" + freight_long);
                getPresenter().LoadSetTakeResult(SettingsAty.this,id,freight,freight_long);
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onItemListener(int choose) {
        if (choose == abulmCameraDialog.TAKEPHOTO) {
            Intent intent = new Intent(this, CameraActivity.class);
            intent.putExtra("type","2");
            startActivity(intent);
            abulmCameraDialog.dismiss();
        } else if (choose == abulmCameraDialog.AUBLUM) {
            RxPermissions rxPermissions = new RxPermissions(this);
            if (!rxPermissions.isGranted(Manifest.permission.CAMERA)) {
                rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Boolean aBoolean) {
                                if (aBoolean) {
                                    EasyPhotos.createAlbum(SettingsAty.this, true, new MyGlideEngin())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                                            .setCount(1)
                                            .setFileProviderAuthority("com.hlhj.funlike_business.cameraProvider")//参数说明：见下方`FileProvider的配置`
                                            .start(TAKE_PHOTO);
                                } else {
                                }


                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            } else {
                EasyPhotos.createAlbum(this, true, new MyGlideEngin())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                        .setCount(1)
                        .setFileProviderAuthority("com.hlhj.funlike_business.cameraProvider")//参数说明：见下方`FileProvider的配置`
                        .start(TAKE_PHOTO);
            }
            abulmCameraDialog.dismiss();
        } else if (choose == abulmCameraDialog.CANCLE) {
            abulmCameraDialog.dismiss();
        }
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getBitmap(BitmapEvent bitmapEvent) throws IOException {
        File file = FileUtils.INSTANCE.createImageFile(bitmapEvent.bitmap, this);
        imgDialog.show();
        getPresenter().LoadUpImgResult(SettingsAty.this,file);
//        Glide.with(this).load(file).into(img_cover);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void refresh(String msg){
        getData();
    }

    public void getData(){
        tv_shopname.setText(spUser.getShopname());
        tv_advert.setText(spUser.getShopAdvert());
        tv_tel.setText(spUser.getShopTel());
        tv_cricle.setText(spUser.getShopCricle()+"KM");
        if (null != spUser.getShopTime() && spUser.getShopTime().length() > 0){
            tv_starttime.setText(spUser.getShopTime().substring(0,spUser.getShopTime().indexOf("~")));
            tv_endtime.setText(spUser.getShopTime().substring(spUser.getShopTime().indexOf("~"),spUser.getShopTime().length()));
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        dataBeanList.clear();
        super.onDestroy();
    }

    public void showTime(){
        TimeDialog shareDialog = new TimeDialog(this);
        startime = tv_starttime.getText().toString();
        endtime = tv_endtime.getText().toString();
        shareDialog.setDeault(startime, endtime.substring(1,endtime.length()));
        shareDialog.show();
    }


    @Override
    public void callback(List<String> result) {
        tv_starttime.setText(result.get(0)+"~");
        tv_endtime.setText(result.get(1));
        getPresenter().LoadTimeResult(SettingsAty.this,result.get(0),result.get(1));
    }

    @Override
    public void showTimeResult(MsgBean msgBean) {
        Toast.makeText(this,msgBean.getMsg().toString(),Toast.LENGTH_SHORT).show();
        SPUser.getUser(getApplication()).setShopTime(tv_starttime.getText().toString() + tv_endtime.getText().toString());
    }

    @Override
    public void showTakeType(List<TakeTypeBean.DataBean> dataBeans) {
        dataBeanList.clear();
        dataBeanList.addAll(dataBeans);
    }

    @Override
    public void showSetTakeResult(MsgBean msgBean) {
        Toast.makeText(this,msgBean.getMsg().toString(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showShopInfo(ShopInfoBean.DataBean dataBean) {
        tv_shopname.setText(dataBean.getShop_name());
        tv_advert.setText(dataBean.getAdvertising());
        Glide.with(SettingsAty.this).load(dataBean.getImg()).into(img_cover);
        tv_address.setText(dataBean.getAddress());
        tv_tel.setText(dataBean.getTel());
        tv_cricle.setText(dataBean.getDistance()+"km");
        tv_takeType.setText(dataBean.getDistribution_name());
        tv_starttime.setText(dataBean.getBusiness_start());
        tv_endtime.setText("~"+dataBean.getBusiness_end());
        SPUser.getUser(getApplication()).setShopImg(dataBean.getImg());

        advert=dataBean.getAdvertising();
        name=dataBean.getShop_name();
        phoneNum=dataBean.getTel();
        circle=dataBean.getDistance();
        freight=dataBean.getFreight();
        freight_long=dataBean.getFreight_long();
    }

    @Override
    public void showUpImgResult(UpImgBean.DataBean dataBean) {
        Toast.makeText(SettingsAty.this,"上传成功",Toast.LENGTH_SHORT).show();
        Glide.with(SettingsAty.this).load(dataBean.getUrl()).into(img_cover);
        imgDialog.dismiss();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)return;
        switch (requestCode){
            case TAKE_PHOTO:
                ArrayList<String> listExtra = data.getStringArrayListExtra(EasyPhotos.RESULT_PATHS);
                File file = new File(listExtra.get(0).toString());
                imgDialog.show();
                getPresenter().LoadUpImgResult(SettingsAty.this,file);
                break;
            case 1000:
                if (resultCode==1001){
                    if(!TextUtils.isEmpty(data.getStringExtra("address"))){
                        tv_address.setText(data.getStringExtra("address"));
                    }
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (imgDialog.isShowing()){
                imgDialog.dismiss();
                Toast.makeText(SettingsAty.this,"取消上传",Toast.LENGTH_SHORT).show();
                return true;
            }else {
                EventBus.getDefault().postSticky("刷新我的界面");
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    /**
//     * 相机
//     *
//     */
//    public void takePhone() {
//        if (ContextCompat.checkSelfPermission(this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat
//                    .requestPermissions(
//                            this,
//                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
//                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
//
//        } else {
//            takePhoto();
//        }
//
//    }
//
//    /**
//     * 相册
//     *
//     */
//    public void choosePhone() {
//        if (ContextCompat.checkSelfPermission(this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat
//                    .requestPermissions(
//                            this,
//                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
//                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
//
//        } else {
//            choosePhoto();
//        }
//    }
//
//    /**
//     * 拍照
//     */
//    private void takePhoto() {
//        /**
//         * 最后一个参数是文件夹的名称，可以随便起
//         */
//        File file = new File(Environment.getExternalStorageDirectory(), "拍照");
//        if (!file.exists()) {
//            file.mkdir();
//        }
//        /**
//         * 这里将时间作为不同照片的名称
//         */
//        output = new File(file, System.currentTimeMillis() + ".jpg");
//
//        /**
//         * 如果该文件夹已经存在，则删除它，否则创建一个
//         */
//        try {
//            if (output.exists()) {
//                output.delete();
//            }
//            output.createNewFile();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        /**
//         * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
//         */
//        imageUri = Uri.fromFile(output);
//        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//        startActivityForResult(intent, CROP_PHOTO);
//
//    }
//
//    /**
//     * 从相册选取图片
//     */
//    private void choosePhoto() {
//        /**
//         * 打开选择图片的界面
//         */
//        Intent intent = new Intent(Intent.ACTION_PICK);
//        intent.setType("image/*");// 相片类型
//        startActivityForResult(intent, PICK_PIC);
//
//    }
//
//    /**
//     * 调用相册和拍照之后的返回
//     */
//    public void onActivityResult(int req, int res, Intent data) {
//        switch (req) {
//            /**
//             * 拍照的请求标志
//             */
//            case CROP_PHOTO:
//                if (res == RESULT_OK) {
//                    try {
//                        /**
//                         * 该uri就是照片文件夹对应的uri
//                         */
//                        Bitmap bit = BitmapFactory
//                                .decodeStream(getContentResolver().openInputStream(imageUri));
//                        img_cover.setImageBitmap(bit);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                break;
//            /**
//             * 从相册中选取图片的请求标志
//             */
//
//            case PICK_PIC:
//                if (res == RESULT_OK) {
//                    try {
//                        /**
//                         * 该uri是上一个Activity返回的
//                         */
//                        imgDialog.show();
//                        Uri uri = data.getData();
//                        Bitmap bit = BitmapFactory
//                                .decodeStream(getContentResolver().openInputStream(uri));
//                        img_cover.setImageBitmap(bit);
//                        File imageFile = FileUtils.INSTANCE.createImageFile(bit, SettingsAty.this);
//                        getPresenter().LoadUpImgResult(SettingsAty.this,imageFile);
//                        img_cover.setImageBitmap(bit);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//                break;
//
//            default:
//                break;
//        }
//    }
//
//    /**
//     * 动态权限
//     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode,
//                                           String[] permissions, int[] grantResults) {
//
//        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE1) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                takephoto();
//            } else {
//                // Permission Denied
//                Toast.makeText(SettingsAty.this, "Permission Denied",
//                        Toast.LENGTH_SHORT).show();
//            }
//        }
//
//        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            } else {
//                // Permission Denied
//                Toast.makeText(SettingsAty.this, "Permission Denied",
//                        Toast.LENGTH_SHORT).show();
//            }
//        }
//    }

}
